package com.ych.service;

import com.ych.bean.ResponseBean;
import com.ych.pojo.LoginYonghu;
import com.ych.utils.JwtUtil;
import com.ych.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginService {
    @Autowired
    private AuthenticationManager manager;
   @Autowired

    private RedisCache redisCache;
    public ResponseBean login(String uname, String psw) {
      // 用 AuthenticationManager的Authenticate方法进行认证
        UsernamePasswordAuthenticationToken token= new UsernamePasswordAuthenticationToken(uname,psw);
        System.out.println("准备登录");
        Authentication authenticate = manager.authenticate(token);  // 会自动进入YonghuService里面的loadUserByUsername()方法进行登录
        if(Objects.isNull(authenticate)){
            throw  new RuntimeException("登录失败");
        }
        //获取当前用户的userid
        LoginYonghu loginUser = (LoginYonghu) authenticate.getPrincipal();
        String userid = loginUser.getYonghu().getYid();

        String jwt = JwtUtil.createJWT(userid);
        Map<String, String> map = new HashMap<>();
        map.put("token",jwt);

        //把完整的用户信息存入redis  userid为key   用户信息为value
        redisCache.setCacheObject("login:"+userid,loginUser);
        return  new ResponseBean(200,"ok",map);
    }
}
